// websocket-log-server.js
const WebSocket = require('ws');
const express = require('express');
const app = express();
const port = 8080;

// HTTP服务器
const server = app.listen(port, () => {
    console.log(`日志服务运行在 http://localhost:${port}`);
});

// WebSocket服务器
const wss = new WebSocket.Server({ server });

// 模拟日志生成器
function generateLog() {
    const levels = ['DEBUG', 'INFO', 'WARN', 'ERROR'];
    const services = ['AuthService', 'Database', 'API', 'Cache', 'Scheduler'];
    const messages = [
        'User login successful',
        'Database connection established',
        'Cache miss for key: user_123',
        'SQL query took 250ms',
        'Invalid request from 192.168.1.100',
        'Failed to connect to Redis'
    ];
    
    const level = levels[Math.floor(Math.random() * levels.length)];
    const service = services[Math.floor(Math.random() * services.length)];
    const message = messages[Math.floor(Math.random() * messages.length)];
    
    return `${new Date().toISOString()} [${level}] ${service} - ${message}`;
}

// 处理WebSocket连接
wss.on('connection', (ws) => {
    console.log('新的客户端连接');
    
    // 每1秒发送一条模拟日志
    const interval = setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
            let s = generateLog();
            console.log('发送--> ' + s);
            ws.send(s);
        }
    }, 1000);
    
    ws.on('close', () => {
        console.log('客户端断开连接');
        clearInterval(interval);
    });
});
